package com.yun.util.yun.utils.http;

import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Scanner;

/**
 * connection servlet

 */
public class CasHttpConnection {

	/**
	 * 连接指定Servlet 并获取响应信息
	 * 
	 * @param urlStr
	 *            指定Servlet url
	 * @param keyVal
	 *            键值对
	 * @return
	 */
	public static String getConnectionResponse(String urlStr,
			Map<String, String> keyVal) {

		String res = "";
		URL url = null;
		HttpURLConnection conn = null;

		try {
			url = new URL(urlStr);
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			conn.setRequestMethod("POST");

			// 发送信息
			OutputStreamWriter out = new OutputStreamWriter(conn
					.getOutputStream(), "UTF-8");
			// 转换请求参数 并发送
			String sendStr = mapToStr(keyVal);
			out.write(sendStr.substring(1));
			out.flush();
			out.close();

			// 接收信息
			Scanner sc = new Scanner(conn.getInputStream());
			if (sc.hasNextLine()) {
				res = res + sc.nextLine();
			}
			sc.close();
		} catch (Exception e) {
			e.printStackTrace();
			return "ERROR";
		}
		return res;
	}

	/**
	 * map 对象转成 String 分隔符为&
	 * 
	 * @param maps
	 * @return
	 */
	private static String mapToStr(Map<String, String> maps) {
		StringBuilder sbBuilder = new StringBuilder();
		String key = "";
		for (String s : maps.keySet()) {
			key = s;
			sbBuilder.append("&").append(key).append("=").append(maps.get(key));
		}
		return sbBuilder.toString();
	}
}